//
//  MSHotelDetailView.m
//  MSJD
//
//  Created by 箭军刘 on 2018/10/14.
//  Copyright © 2018年 xiangbo. All rights reserved.
//

#import "MSHotelDetailView.h"

#import "MSDetailViewController.h"
// FIXME:
#import "MSHomeFilterViewController.h"

#import "MSHomeHeadView.h"
#import "MSHotelCell.h"
#import "MSHotelSectionView.h"
#import "MSTemplateCellUtil.h"
#import "MSBaseShowCell.h"
#import "MSHotelEmptyCell.h"

#import "MSHotelDataSource.h"
#import "MSSearchDataSource.h"

#import "NSDate+Extension.h"

@interface MSHotelDetailView()
<UITableViewDelegate, UITableViewDataSource>

@property (nonatomic, strong) MSHotelSectionView *sectionView;

@property (nonatomic, strong) NSMutableDictionary *identifierDic;

@property (nonatomic, copy) NSArray *templateArr; // 模板数组
@property (nonatomic, copy) NSArray *hotelList; // 酒店列表数据

@property (nonatomic, assign) NSInteger page;
@property (nonatomic, assign) NSInteger pageSize;

@property (nonatomic, copy) NSDictionary *filterInfo; // 筛选字典
@property (nonatomic, strong) NSMutableDictionary *selectFilterInfo; // 选中的筛选数组

@property (nonatomic, copy) NSDictionary *daySelectorDic; // 选择的退房和住房字典
@property (nonatomic, copy) NSString *cityStr; // 城市名称

@end

@implementation MSHotelDetailView {
    BOOL _isShowFilterEmptyView; // 是否展示筛选数据为空的界面
    
    // FIXME:
    BOOL _isFristLoad; // 是否第一次加载
}

- (instancetype)initWithFrame:(CGRect)frame {
    if (self = [super initWithFrame:frame]) {
        
        _isFristLoad = YES;
        _isShowFilterEmptyView = NO;
        self.filterInfo = nil;
        
        self.backgroundColor = [UIColor clearColor];
        
        [self addSubview:self.tableView];

        [self.tableView mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.left.bottom.right.offset(0);
        }];
         
        [self loadData];
    }
    return self;
}
/** 加载数据 */
- (void)loadData {
    self.page = 1;
    self.pageSize = 6;
    self.hotelList = [NSArray array];
    [self.tableView.mj_header beginRefreshing];
}

/** 查询酒店信息 */
- (void)loadHotelInfoFromServer {
    _WEAKSELF
    [MSHotelDataSource queryHotelDataWithSuccess:^(NSArray * _Nonnull responseInfo) {
        [weakSelf stopRefresh];
        self.templateArr = responseInfo;
        [self.tableView reloadData];
        
        if (_isFristLoad) {
            if (weakSelf.hotelList.count > 0) {
                return;
            }
            _isFristLoad = NO;
            [weakSelf loadFilterListDataFromServer];
        }
    } failure:^(NSError * _Nonnull error) {
        [weakSelf stopRefresh];
        NSString *errorMsg = error.localizedDescription?:@"查询酒店推荐信息失败";
        [MBProgressHUD showDefaultHUDWithText:errorMsg toView:self];
    }];
}
/** 查询筛选项数据 */
- (void)loadFilterListDataFromServer {
    
    _WEAKSELF
    [MSHotelDataSource queryFilterListWithKind:1 success:^(NSDictionary * _Nonnull responseInfo) {
        weakSelf.filterInfo = [MSSafeObject dictionaryInfo:responseInfo[@"data"]];
        [weakSelf loadHotelListFromServer];
    } failure:^(NSError * _Nonnull error) {
        NSString *errorMsg = error.localizedDescription?:@"查询筛选信息失败";
        [MBProgressHUD showDefaultHUDWithText:errorMsg toView:self];
    }];
}

/** 查询酒店筛选列表数据 */
- (void)loadHotelListFromServer {
    // 查询默认筛选数据
    NSMutableDictionary *filterParam = [MSSafeObject dictionaryInfo:self.selectFilterInfo].mutableCopy;
    if (![MSSafeObject isNull:self.cityStr]) {
        [filterParam setObject:self.cityStr forKey:@"city"];
    }
    _WEAKSELF
    [MSSearchDataSource searchContentListWithFilterParam:filterParam page:self.page size:self.pageSize success:^(NSDictionary * _Nonnull responseInfo) {
        [weakSelf stopRefresh];
        [weakSelf loadHotelListSuccess:responseInfo];
    } failure:^(NSError * _Nonnull error) {
        [weakSelf stopRefresh];
        NSString *errorMsg = error.localizedDescription?:@"查询酒店列表失败";
        [MBProgressHUD showDefaultHUDWithText:errorMsg toView:weakSelf];
    }];
}

#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 2;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    if (section == 0) {
        return self.templateArr.count;
    }
    if (self.hotelList.count < 1 && self.filterInfo) {
        return 1;
    }
    return self.hotelList.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row > self.templateArr.count) {
            return [UITableViewCell alloc];
        }
        MSFoodData *moduleData;
        if (self.templateArr.count > indexPath.row) {
            moduleData = self.templateArr[indexPath.row];
        }
        NSString *identifier = moduleData.showType;
        NSString *className  =  self.identifierDic[identifier];
        if (!className) {
            identifier = NSStringFromClass(MSBaseShowCell.class);
        }
        MSBaseShowCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier forIndexPath:indexPath];
        if (!cell.detailView) {
            Class detailClass = NSClassFromString(className);
            if (detailClass) {
                cell.detailView = [[detailClass alloc] init];
            }
        }
        if ([cell.detailView conformsToProtocol:@protocol(MSDetailViewDelegate)]) {
            [(id<MSDetailViewDelegate>)cell.detailView configData:moduleData indexPath:indexPath];
        }

        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        return cell;
    }
    // 酒店列表cell
    MSHotelCell *cell = [tableView dequeueReusableCellWithIdentifier:@"MSHotelCell"];
    if (self.hotelList.count > indexPath.row) {
        NSDictionary *searchDic = self.hotelList[indexPath.row];
        MSFoodDetailData *detailData = [MSFoodDetailData modelWithJSON:searchDic];
        [cell refreshHotelCellWithData:detailData isFilter:YES];
        return cell;
    } else {
        // 空cell
        MSHotelEmptyCell *emptyCell = [tableView dequeueReusableCellWithIdentifier:@"emptyCell"];
        return emptyCell;
    }
}

#pragma mark - UITableViewDelegate
// 点击方法
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    // 点击了某一行
    if (indexPath.section == 1 && indexPath.row < self.hotelList.count) {
        MSFoodDetailData *detailData = [MSFoodDetailData modelWithJSON:self.hotelList[indexPath.row]];
        [MSJumpConn jumpToMSDetailViewController:detailData];
    }
}

// row的高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    if (indexPath.section == 0) {
        if (indexPath.row > self.templateArr.count) {
            return CGFLOAT_MIN;
        }
        MSFoodData *data = self.templateArr[indexPath.row];
//        if ([data.showType isEqualToString:@"db_vimg"]) {
//            return [MSTemplateCellUtil getTemplateCellSize:data.showType].height + 44;
//        }
        return  [MSTemplateCellUtil getTemplateHeight:data.showType];
    }
    if (self.hotelList.count < 1) {
        return 60;
    }
    return 137.0f;
}

// section的高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return CGFLOAT_MIN;
    }
    if (_isFristLoad) {
        return CGFLOAT_MIN;
    }
    return 80.0;
}
// section的view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
    if (section == 0) {
        return nil;
    }
    if (_isFristLoad) {
        return nil;
    }
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0.0, MS_SCREEN_WIDTH, 80.0)];
    headView.backgroundColor = [UIColor clearColor];
    
//    self.filterView.frame = CGRectMake(0, 0, MS_SCREEN_WIDTH, 36.0);
    [headView addSubview:self.sectionView];
    [self.sectionView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.bottom.right.offset(0);
        make.top.offset(-6);
    }];
    return headView;
}

#pragma mark - Event Response
/** 头部刷新 */
- (void)headerRefresh {
    [self loadHotelInfoFromServer];
}
/** 底部刷新 */
- (void)footerRefresh {
    [self loadHotelListFromServer];
}

#pragma mark - Public Method

- (void)refreshHotelLocalTitle {
    if (self.headView) {
        [self.headView refreshLocalTitle];
    }
}

/** 修改时间选择 */
- (void)changeDate:(NSDictionary *)date {
    self.daySelectorDic = date;
    if (self.sectionView) {
        [self.sectionView refreshSectionDayLabel:date];
    }
}
/** 修改搜索内容 */
- (void)changeFilterContent:(NSString *)filterContent {
    // 将filter控件滑动到头部
    [self scrollToSectionViewCompletion:nil];
    // 请求数据
    self.selectFilterInfo = @{@"keyword":[MSSafeObject stringInfo:filterContent]}.mutableCopy;
    self.page = 1;
    self.hotelList = [NSArray array];
    [self loadHotelListFromServer];

    // 清空筛选控件里的选中数据的数据
    if (self.sectionView) {
        [self.sectionView resetFilterSelectData];
        [self.sectionView changeSearchTitle:filterContent];
    }
}
/** 修改城市 */
- (void)changeCity:(NSString *)cityTitle {
    self.cityStr = cityTitle;
    if (self.sectionView) {
        [self.sectionView refreshCityTitle:cityTitle];
    }
}

- (NSString *)showSearchContent {
    return [MSSafeObject stringInfo:self.selectFilterInfo[@"keyword"]];
}

#pragma mark - Private Method
/** 查询酒店列表数据 */
- (void)loadHotelListSuccess:(NSDictionary *)searchData {
    NSInteger page = [searchData[@"page"] integerValue];
    NSInteger totalPage = [searchData[@"totalPage"] integerValue];
    if (page >= totalPage) {
        [self.tableView.mj_footer endRefreshingWithNoMoreData];
    } else {
        self.page ++;
    }
    NSMutableArray *tempHotelList = [NSMutableArray arrayWithArray:self.hotelList];
    [tempHotelList addObjectsFromArray:searchData[@"rows"]];
    self.hotelList = tempHotelList.copy;
//    [self.tableView reloadData];
    [self.tableView reloadSections:[NSIndexSet indexSetWithIndex:1] withRowAnimation:UITableViewRowAnimationNone];
}

/** 选中了某一行cell的侧滑后的按钮(type: 0 分享 1：删除， row：cell的indexPath.row) */
- (void)didSelectCellEditButtonWithType:(NSInteger)type row:(NSInteger)row {
    [self.tableView setEditing:NO animated:YES];
    if (type == 0) {
        // 分享
        
    }
}
/** 停止刷新 */
- (void)stopRefresh {
    if ([self.tableView.mj_header isRefreshing]) {
        [self.tableView.mj_header endRefreshing];
    }
    if ([self.tableView.mj_footer isRefreshing]) {
        [self.tableView.mj_footer endRefreshing];
    }
}
/** 根据筛选控件的状态来刷新tableView */
- (void)refreshTableViewWithFilterStatus:(BOOL)isShow {
    if (isShow) {
        _WEAKSELF
        [self scrollToSectionViewCompletion:^{
            if (weakSelf.sectionView) {
                [weakSelf.sectionView showSectionFilterView];
            }
        }];
        self.tableView.scrollEnabled = NO;
    } else {
        self.tableView.scrollEnabled = YES;
    }
}
/** 滚动到section的位置 */
- (void)scrollToSectionViewCompletion:(void (^)(void))completion {
    CGFloat headViewY = CGRectGetMinY(self.sectionView.superview.frame);
    _WEAKSELF
    [UIView animateWithDuration:0.25 animations:^{
        weakSelf.tableView.contentOffset = CGPointMake(0, headViewY);
    } completion:^(BOOL finished) {
        if (completion) {
            completion();
        }
    }];
}

/** section顶部按钮点击 */
- (void)sectionTopSelectButtonClick:(MSHotelSectionButtonType)type {
    if (self.PresentBlock) {
        NSDictionary *contentDic = (type == MSHotelSectionButtonTypeTime)?self.daySelectorDic:nil;
        self.PresentBlock((MSHotelDetailPushType)type, contentDic);
    }
}

#pragma mark - Setters And Getters

- (NSMutableDictionary *)identifierDic {
    if (!_identifierDic) {
        _identifierDic = [NSMutableDictionary dictionary];
    }
    return _identifierDic;
}

- (NSDictionary *)daySelectorDic {
    if (!_daySelectorDic) {
        _daySelectorDic = @{@"current":[MSSafeObject stringInfo:[NSDate currentDay]],
                            @"tomorrow":[MSSafeObject stringInfo:[NSDate tomorrowDay]]};
    }
    return _daySelectorDic;
}

- (MSHomeHeadView *)headView {
    if (!_headView) {
        _headView = [[MSHomeHeadView alloc] initWithFrame:CGRectZero headType:MSHeadViewTypeHotel];
    }
    return _headView;
}

- (MSHotelSectionView *)sectionView {
    if (!_sectionView) {
        _sectionView = [MSHotelSectionView loadHotelSectionViewWithFilterInfo:self.filterInfo];
        _WEAKSELF
        _sectionView.FilterShowBlock = ^(BOOL isShow) {
            [weakSelf refreshTableViewWithFilterStatus:isShow];
        };
        [_sectionView refreshSectionDayLabel:self.daySelectorDic];
        // 搜索顶部按钮点击
        _sectionView.SectionTopButtonClickBlock = ^(MSHotelSectionButtonType type) {
            [weakSelf sectionTopSelectButtonClick:type];
        };
        // 修改筛选内容回调
        _sectionView.RefreshFilterBlock = ^(NSDictionary * _Nonnull selectFilterDic) {
            weakSelf.selectFilterInfo = selectFilterDic.mutableCopy;
            // 重新请求筛选数据
            weakSelf.page = 1;
            weakSelf.hotelList = [NSArray array];
            [weakSelf loadHotelListFromServer];
        };
        _sectionView.SearchClearButtonClickBlock = ^{
            [weakSelf.selectFilterInfo removeAllObjects];
            // 重新请求筛选数据
            weakSelf.page = 1;
            weakSelf.hotelList = [NSArray array];
            [weakSelf loadHotelListFromServer];
        };
    }
    return _sectionView;
}

- (UITableView *)tableView {
    if (!_tableView) {
        
        _tableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.backgroundColor = [UIColor clearColor];
        // 注册同美食一样的特殊类cell
//        [_tableView registerClass:[MSBaseShowCell class] forCellReuseIdentifier:NSStringFromClass([MSBaseShowCell class])];
        for (NSString *key in MSIdentifierDic.allKeys) {
            [self.identifierDic setObject:MSIdentifierDic[key] forKey:key];
            [_tableView registerClass:MSBaseShowCell.class forCellReuseIdentifier:key];
        }
        [_tableView registerClass:MSBaseShowCell.class forCellReuseIdentifier:@"MSBaseShowCell"];
        
        // 筛选列表cell
        [_tableView registerNib:[UINib nibWithNibName:@"MSHotelCell" bundle:nil] forCellReuseIdentifier:@"MSHotelCell"];
        [_tableView registerClass:MSHotelEmptyCell.class forCellReuseIdentifier:@"emptyCell"];
        
        // 设置头部view
        _tableView.tableHeaderView = self.headView;
        _tableView.tableHeaderView.frame = CGRectMake(0, 0, MS_SCREEN_WIDTH, 72);
        
        MJRefreshBackNormalFooter *footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(footerRefresh)];
        footer.activityIndicatorViewStyle = UIActivityIndicatorViewStyleWhite;
        _tableView.mj_footer = footer;
        
        MJRefreshStateHeader *header = [MJRefreshStateHeader headerWithRefreshingTarget:self refreshingAction:@selector(headerRefresh)];
        header.stateLabel.textColor = MSThemeColor;
        header.lastUpdatedTimeLabel.alpha = 1.0;
        _tableView.mj_header = header;
    }
    return _tableView;
}

- (NSMutableDictionary *)selectFilterInfo {
    if (!_selectFilterInfo) {
        _selectFilterInfo = [NSMutableDictionary dictionary];
    }
    return _selectFilterInfo;
}

@end
